package pi.client.gui;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class MyPanelLogin extends MyPanelBase {
	private JTextField usernameTextField;
	private JButton registerNameButton;
	private ActionListener connectButtonEvent;

	private boolean drawInvalidUsername;

	public MyPanelLogin(final MyMainPanel mainPanel, String backgroundFilename,
			int width, int height) {
		super(mainPanel, backgroundFilename, width, height);
		setLayout(null);

		usernameTextField = new JTextField();
		usernameTextField.setBounds(400, 160, 100, 30);

		registerNameButton = new JButton("Register");
		registerNameButton.setBounds(330, 220, 140, 30);

		connectButtonEvent = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				if (usernameTextField.getText().length() > 0) {
					String text = usernameTextField.getText();
					if (text.length() < 10) {
						drawInvalidUsername = false;
						mainPanel.playerMe.username = text;
						mainPanel.program.frame
								.setTitle("King of Wars - Player " + text);
						// mainPanel.SetCurrentPanel(mainPanel.perfilPanel);
						mainPanel.SetCurrentPanel(mainPanel.preGamePanel);
					} else {
						drawInvalidUsername = true;
					}
				}
				repaint();
			}
		};
		registerNameButton.addActionListener(connectButtonEvent);

		add(usernameTextField);
		add(registerNameButton);

		drawInvalidUsername = false;
	}

	@Override
	protected void Draw(Graphics g) {
		super.Draw(g);

		Color rect = new Color(200, 200, 200, 128);

		g.setColor(rect);
		g.fillRect(285, 160, 100, 30);
		g.setColor(Color.white);
		g.drawString("Username", usernameTextField.getX() - 95,
				usernameTextField.getY() + 20);

		if (drawInvalidUsername == true) {
			String msgError = "Username is too long!";
			FontMetrics fm = g.getFontMetrics();
			int stringWidth = fm.stringWidth(msgError);
			int stringHeight = fm.getHeight();
			
			g.setColor(new Color(255, 20, 20, 128));
			g.fillRect(width/2 - stringWidth/2 - 10, 280 - stringHeight/2, stringWidth+20, stringHeight +10);
			g.setColor(Color.white);
			g.drawString(msgError, width/2 - stringWidth/2, 290);
		}

		g.setColor(Color.white);		
		String msg = "Register an username:";
		FontMetrics fm = g.getFontMetrics();
		int stringWidth = fm.stringWidth(msg);

		g.setColor(Color.white);
		g.drawString(msg, width/2 - stringWidth/2, 120);
	}
}